import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class Logic extends GetxController {
  late WebViewController _webViewController = WebViewController();

  WebViewController get webViewController => _webViewController;

  // BuildContext get context = ;

  void setWebViewController(WebViewController controller) {
    _webViewController = controller;
  }

  void reload() {
    _webViewController.reload();
  }

  void go(String url) {
    Uri uri = Uri.parse(url);
    _webViewController.loadRequest(uri); // 加载指定的 URL
  }

  void goForward() {
    _webViewController.goForward();
  }

  void goBack() {
    _webViewController.goBack();
  }

  Future<bool> canGoBack() async {
    return await _webViewController.canGoBack();
  }

  Future<bool> canGoForward() async {
    return await _webViewController.canGoForward();
  }

  final TextEditingController urlController =
      TextEditingController(text: 'https://www.bing.com'); // 默认地址
  String currentUrl = '';

  late final Color backgroundColor = Color(0x00000000);
  late final JavaScriptMode javaScriptMode = JavaScriptMode.unrestricted;

  @override
  void initState() {
    late final PlatformWebViewControllerCreationParams params;
    params = const PlatformWebViewControllerCreationParams();
    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(params);
    controller
      ..setJavaScriptMode(javaScriptMode)
      ..setBackgroundColor(backgroundColor)
      ..setNavigationDelegate(
        NavigationDelegate(
          // 各种触发时间

          // 加载前进行url 地址判断
          onNavigationRequest: (NavigationRequest request) {
            String newUrl = _processUrl(request.url);
            if (newUrl != request.url) {
              controller.loadRequest(Uri.parse(newUrl)); // 重新加载替换后的 URL
              return NavigationDecision.prevent; // 阻止原始请求
            }
            return NavigationDecision.navigate; // 允许导航
          },
        ),
      )
      // ..addJavaScriptChannel(
      //   'Toaster',
      //   onMessageReceived: (JavaScriptMessage message) {
      //     ScaffoldMessenger.of(context).showSnackBar(
      //       SnackBar(content: Text(message.message)),
      //     );
      //   },
      // )
      ..loadRequest(Uri.parse(urlController.text));

    // #docregion platform_features
    // if (controller.platform is AndroidWebViewController) {
    // AndroidWebViewController.enableDebugging(true);
    //   (controller.platform as AndroidWebViewController)
    //       .setMediaPlaybackRequiresUserGesture(false);
    // }
    // #enddocregion platform_features

    _webViewController = controller;
  }

  // 检查并处理初始 URL
  String _processUrl(String url) {
    // 使用 // 分割 URL
    List<String> parts = url.split('//');

    if (parts.length == 1) {
      // 如果只有一个部分，添加 https:// 前缀
      return 'https://$url';
    } else {
      // 如果有多个部分，用 https 替换第一个部分（即协议部分）
      String newUrl = 'https://${parts.sublist(1).join('//')}';
      return newUrl;
    }
  }
}
